// 页面数据检查工具
// 用于诊断数据显示问题
function dataDebugger() {
    // 获取测试数据
    fetch('/api/test-data')
        .then(response => response.json())
        .then(data => {
            console.log('===== 数据诊断工具 =====');
            console.log('原始API数据:', data);

            // 适配物模型数据结构
            let adapted = {};
            if (data && data.Data && data.Data.List && Array.isArray(data.Data.List.PropertyStatusInfo)) {
                data.Data.List.PropertyStatusInfo.forEach(item => {
                    if (item.Identifier && item.Value !== undefined) {
                        // 统一转为数字（如有需要）
                        let v = item.Value;
                        if (item.DataType === 'int' && typeof v === 'string' && !isNaN(Number(v))) {
                            v = Number(v);
                        }
                        adapted[item.Identifier] = v;
                    }
                });
                console.log('适配后的物模型数据:', adapted);
            } else if (data.traditional_format) {
                // 使用传统格式备用
                if (data.traditional_format.devices && data.traditional_format.devices.device1) {
                    adapted = data.traditional_format.devices.device1;
                }
                console.log('使用传统格式备用数据:', adapted);
            } else {
                console.warn('未检测到物模型或传统数据结构，使用原始数据');
                adapted = data;
            }

            // 添加数据可视化到页面（传递适配后的对象）
            addVisualDebugger(adapted);

            // 分析数据结构
            console.log('\n==== 数据结构分析 ====');
            if (adapted && typeof adapted === 'object') {
                console.log('字段列表:', Object.keys(adapted));
                console.log('心率值:', adapted.radar_heartrate, typeof adapted.radar_heartrate);
                console.log('呼吸频率:', adapted.radar_breath, typeof adapted.radar_breath);
                console.log('温度:', adapted.temp, typeof adapted.temp);
                console.log('湿度:', adapted.humidity, typeof adapted.humidity);
            } else {
                console.warn('适配后数据不是有效对象');
            }
            
            // 收集页面显示值
            console.log('\n==== 页面显示值分析 ====');
            const displayValues = {
                heartRate: document.getElementById('heartRate').textContent,
                breathRate: document.getElementById('breathRate').textContent,
                roomTemp: document.getElementById('roomTemp').textContent,
                humidity: document.getElementById('humidity').textContent
            };
            console.log('页面显示值:', displayValues);
            
            // 显示值是否为占位符
            const allPlaceholders = Object.values(displayValues).every(val => val === '--');
            if (allPlaceholders) {
                console.warn('⚠️ 所有显示值均为占位符(--)\n');
            }
            
            // 测试数据访问路径
            console.log('\n==== 数据访问路径测试 ====');
            // 1. 直接路径（物模型字段，适配后）
            const directPath = {
                heartRate: adapted.radar_heartrate,
                breathRate: adapted.radar_breath,
                roomTemp: adapted.temp,
                humidity: adapted.humidity
            };
            console.log('直接路径:', directPath);
            
            // 2. data子对象路径（适配后无嵌套，全部为undefined）
            const dataSubPath = {
                heartRate: undefined,
                breathRate: undefined,
                roomTemp: undefined,
                humidity: undefined
            };
            console.log('data子对象路径:', dataSubPath);
            
            // 3. 字段名称变体
            const fieldVariants = {
                heartRate: {
                    radar_heartrate: adapted.radar_heartrate
                },
                breathRate: {
                    radar_breath: adapted.radar_breath
                },
                temp: adapted.temp,
                humidity: adapted.humidity
            };
            console.log('字段名称变体:', fieldVariants);
            
            // 4. 测试updateElementText
            console.log('\n==== 元素更新函数测试 ====');
            // 复制updateElementText函数
            const testUpdate = function(id, value) {
                const element = document.getElementById(id);
                if (!element) {
                    console.warn(`未找到元素: ${id}`);
                    return false;
                }
                
                const oldValue = element.textContent;
                
                // 准备日志信息
                let result = {
                    元素: id,
                    原值: oldValue,
                    新值: value,
                    新值类型: typeof value,
                    转换结果: value
                };
                
                // 值处理与格式化
                if (value === undefined || value === null || value === '') {
                    result.转换结果 = '--';
                    result.说明 = '空值转为占位符';
                } else if (typeof value === 'number') {
                    // 数字格式化
                    switch(id) {
                        case 'heartRate':
                            result.转换结果 = Math.round(value);
                            result.说明 = '四舍五入整数';
                            break;
                        case 'breathRate':
                            result.转换结果 = Math.round(value);
                            result.说明 = '四舍五入整数';
                            break;
                        case 'roomTemp':
                            result.转换结果 = value.toFixed(1);
                            result.说明 = '保留一位小数';
                            break;
                        case 'humidity':
                            result.转换结果 = Math.round(value);
                            result.说明 = '四舍五入整数';
                            break;
                        default:
                            result.转换结果 = value;
                            result.说明 = '保持原值';
                    }
                } else {
                    result.转换结果 = value;
                    result.说明 = '保持原值';
                }
                
                console.log(result);
                return result;
            };
            
            // 测试更新不同值
            console.log('测试心率更新:');
            testUpdate('heartRate', adapted.radar_heartrate);
            
            console.log('测试呼吸频率更新:');
            testUpdate('breathRate', adapted.radar_breath);
            
            console.log('测试室温更新:');
            testUpdate('roomTemp', adapted.temp);
            
            console.log('测试湿度更新:');
            testUpdate('humidity', adapted.humidity);
            
            // 诊断结果
            console.log('\n==== 诊断结果 ====');
            
            // 检查API数据是否有效（物模型字段，适配后）
            const hasValidData = adapted && (
                adapted.radar_heartrate !== undefined ||
                adapted.radar_breath !== undefined ||
                adapted.temp !== undefined ||
                adapted.humidity !== undefined
            );
            
            if (hasValidData && allPlaceholders) {
                console.error('❌ 关键问题: API返回了有效数据，但页面显示仍为占位符');
                console.log('可能的原因:');
                console.log('1. 数据绑定路径错误 - 检查updateDisplayData函数');
                console.log('2. 数据格式转换问题 - 检查updateElementText函数');
                console.log('3. DOM更新失败 - 检查控制台是否有错误');
            } else if (!hasValidData) {
                console.warn('⚠️ API未返回有效数据，检查后端数据源');
            } else {
                console.log('✅ 数据显示正常');
            }
        })
        .catch(error => {
            console.error('诊断工具错误:', error);
        });
}

// 添加可视化调试器
function addVisualDebugger(data) {
    // 移除已有的可视化调试器
    const existingDebugger = document.getElementById('visual-debugger');
    if (existingDebugger) {
        existingDebugger.remove();
    }
    
    // 创建可视化调试器容器
    const debuggerContainer = document.createElement('div');
    debuggerContainer.id = 'visual-debugger';
    debuggerContainer.style.position = 'fixed';
    debuggerContainer.style.top = '50px';
    debuggerContainer.style.left = '20px';
    debuggerContainer.style.zIndex = '9999';
    debuggerContainer.style.backgroundColor = 'rgba(0, 0, 0, 0.85)';
    debuggerContainer.style.color = 'white';
    debuggerContainer.style.padding = '15px';
    debuggerContainer.style.borderRadius = '10px';
    debuggerContainer.style.boxShadow = '0 0 15px rgba(0, 0, 0, 0.5)';
    debuggerContainer.style.maxWidth = '500px';
    debuggerContainer.style.maxHeight = '80vh';
    debuggerContainer.style.overflow = 'auto';
    debuggerContainer.style.fontFamily = 'monospace';
    debuggerContainer.style.fontSize = '12px';
    
    // 添加标题和关闭按钮
    const header = document.createElement('div');
    header.style.display = 'flex';
    header.style.justifyContent = 'space-between';
    header.style.alignItems = 'center';
    header.style.marginBottom = '10px';
    
    const title = document.createElement('h3');
    title.textContent = '数据可视化调试器';
    title.style.margin = '0';
    title.style.color = '#3498db';
    
    const closeButton = document.createElement('button');
    closeButton.textContent = '×';
    closeButton.style.backgroundColor = 'transparent';
    closeButton.style.border = 'none';
    closeButton.style.color = 'white';
    closeButton.style.fontSize = '20px';
    closeButton.style.cursor = 'pointer';
    closeButton.onclick = function() {
        debuggerContainer.remove();
    };
    
    header.appendChild(title);
    header.appendChild(closeButton);
    debuggerContainer.appendChild(header);
    
    // 创建数据流程可视化
    const flowContainer = document.createElement('div');
    
    // 1. API数据
    const apiData = document.createElement('div');
    apiData.style.marginBottom = '15px';
    apiData.style.padding = '10px';
    apiData.style.backgroundColor = '#2c3e50';
    apiData.style.borderRadius = '5px';
    
    const apiTitle = document.createElement('div');
    apiTitle.textContent = '1. API数据';
    apiTitle.style.fontWeight = 'bold';
    apiTitle.style.marginBottom = '5px';
    apiTitle.style.color = '#3498db';
    
    const apiContent = document.createElement('div');
    if (data && typeof data === 'object') {
        apiContent.innerHTML = `
            <div style="margin-bottom:8px;"><b>物模型数据:</b> radar_heartrate=${data.radar_heartrate || '--'}, radar_breath=${data.radar_breath || '--'}, temp=${data.temp || '--'}, humidity=${data.humidity || '--'}</div>
        `;
    } else {
        apiContent.textContent = '无有效数据';
        apiContent.style.color = '#e74c3c';
    }
    
    apiData.appendChild(apiTitle);
    apiData.appendChild(apiContent);
    flowContainer.appendChild(apiData);
    
    // 2. 数据处理
    const dataProcessing = document.createElement('div');
    dataProcessing.style.marginBottom = '15px';
    dataProcessing.style.padding = '10px';
    dataProcessing.style.backgroundColor = '#2c3e50';
    dataProcessing.style.borderRadius = '5px';
    
    const processingTitle = document.createElement('div');
    processingTitle.textContent = '2. 数据处理';
    processingTitle.style.fontWeight = 'bold';
    processingTitle.style.marginBottom = '5px';
    processingTitle.style.color = '#3498db';
    
    const processingContent = document.createElement('div');
    
    // 模拟处理过程
    const processedData = {};
    
    if (data && typeof data === 'object') {
        // 心率处理
        let hrProcessed = '-- (未找到)';
        let hrStatus = 'error';
        if (data.radar_heartrate !== undefined) {
            if (typeof data.radar_heartrate === 'number') {
                hrProcessed = Math.round(data.radar_heartrate);
                hrStatus = 'success';
            } else if (typeof data.radar_heartrate === 'string') {
                const hrNum = parseFloat(data.radar_heartrate);
                if (!isNaN(hrNum)) {
                    hrProcessed = Math.round(hrNum);
                    hrStatus = 'success';
                } else {
                    hrProcessed = `无法转换 "${data.radar_heartrate}"`;
                    hrStatus = 'warning';
                }
            }
        }
        
        // 呼吸频率处理
        let brProcessed = '-- (未找到)';
        let brStatus = 'error';
        if (data.radar_breath !== undefined) {
            if (typeof data.radar_breath === 'number') {
                brProcessed = Math.round(data.radar_breath);
                brStatus = 'success';
            } else if (typeof data.radar_breath === 'string') {
                const brNum = parseFloat(data.radar_breath);
                if (!isNaN(brNum)) {
                    brProcessed = Math.round(brNum);
                    brStatus = 'success';
                } else {
                    brProcessed = `无法转换 "${data.radar_breath}"`;
                    brStatus = 'warning';
                }
            }
        }
        
        // 温度处理
        let tempProcessed = '-- (未找到)';
        let tempStatus = 'error';
        if (data.temp !== undefined) {
            if (typeof data.temp === 'number') {
                tempProcessed = data.temp.toFixed(1);
                tempStatus = 'success';
            } else if (typeof data.temp === 'string') {
                const tempNum = parseFloat(data.temp);
                if (!isNaN(tempNum)) {
                    tempProcessed = tempNum.toFixed(1);
                    tempStatus = 'success';
                } else {
                    tempProcessed = `无法转换 "${data.temp}"`;
                    tempStatus = 'warning';
                }
            }
        }
        
        // 湿度处理
        let humProcessed = '-- (未找到)';
        let humStatus = 'error';
        if (data.humidity !== undefined) {
            if (typeof data.humidity === 'number') {
                humProcessed = Math.round(data.humidity);
                humStatus = 'success';
            } else if (typeof data.humidity === 'string') {
                const humNum = parseFloat(data.humidity);
                if (!isNaN(humNum)) {
                    humProcessed = Math.round(humNum);
                    humStatus = 'success';
                } else {
                    humProcessed = `无法转换 "${data.humidity}"`;
                    humStatus = 'warning';
                }
            }
        }
        processedData.heart_rate = hrProcessed;
        processedData.breath_rate = brProcessed;
        processedData.temperature = tempProcessed;
        processedData.humidity = humProcessed;
        
        processingContent.innerHTML = `
            <div style="margin-bottom:5px;">
                <b>心率:</b> ${data.radar_heartrate || '--'} 
                <span style="color:${hrStatus === 'success' ? '#2ecc71' : hrStatus === 'warning' ? '#f39c12' : '#e74c3c'}">
                    → ${hrProcessed}
                </span>
            </div>
            <div style="margin-bottom:5px;">
                <b>呼吸:</b> ${data.radar_breath || '--'} 
                <span style="color:${brStatus === 'success' ? '#2ecc71' : brStatus === 'warning' ? '#f39c12' : '#e74c3c'}">
                    → ${brProcessed}
                </span>
            </div>
            <div style="margin-bottom:5px;">
                <b>温度:</b> ${data.temp || '--'} 
                <span style="color:${tempStatus === 'success' ? '#2ecc71' : tempStatus === 'warning' ? '#f39c12' : '#e74c3c'}">
                    → ${tempProcessed}
                </span>
            </div>
            <div>
                <b>湿度:</b> ${data.humidity || '--'} 
                <span style="color:${humStatus === 'success' ? '#2ecc71' : humStatus === 'warning' ? '#f39c12' : '#e74c3c'}">
                    → ${humProcessed}
                </span>
            </div>
        `;
    } else {
        processingContent.textContent = '无数据可处理';
        processingContent.style.color = '#e74c3c';
    }
    
    dataProcessing.appendChild(processingTitle);
    dataProcessing.appendChild(processingContent);
    flowContainer.appendChild(dataProcessing);
    
    // 3. 页面显示
    const pageDisplay = document.createElement('div');
    pageDisplay.style.marginBottom = '15px';
    pageDisplay.style.padding = '10px';
    pageDisplay.style.backgroundColor = '#2c3e50';
    pageDisplay.style.borderRadius = '5px';
    
    const displayTitle = document.createElement('div');
    displayTitle.textContent = '3. 页面显示';
    displayTitle.style.fontWeight = 'bold';
    displayTitle.style.marginBottom = '5px';
    displayTitle.style.color = '#3498db';
    
    const displayContent = document.createElement('div');
    
    // 获取页面显示值
    const displayValues = {
        heartRate: document.getElementById('heartRate').textContent,
        breathRate: document.getElementById('breathRate').textContent,
        roomTemp: document.getElementById('roomTemp').textContent,
        humidity: document.getElementById('humidity').textContent
    };
    
    // 比较处理值和显示值
    const compareHeartRate = processedData.heart_rate == displayValues.heartRate;
    const compareBreathRate = processedData.breath_rate == displayValues.breathRate;
    const compareTemp = processedData.temperature == displayValues.roomTemp;
    const compareHumidity = processedData.humidity == displayValues.humidity;
    
    displayContent.innerHTML = `
        <div style="margin-bottom:5px;">
            <b>心率:</b> 
            <span style="color:${compareHeartRate ? '#2ecc71' : '#e74c3c'}">
                ${displayValues.heartRate} ${compareHeartRate ? '✓' : '✗'}
            </span>
        </div>
        <div style="margin-bottom:5px;">
            <b>呼吸:</b> 
            <span style="color:${compareBreathRate ? '#2ecc71' : '#e74c3c'}">
                ${displayValues.breathRate} ${compareBreathRate ? '✓' : '✗'}
            </span>
        </div>
        <div style="margin-bottom:5px;">
            <b>温度:</b> 
            <span style="color:${compareTemp ? '#2ecc71' : '#e74c3c'}">
                ${displayValues.roomTemp} ${compareTemp ? '✓' : '✗'}
            </span>
        </div>
        <div>
            <b>湿度:</b> 
            <span style="color:${compareHumidity ? '#2ecc71' : '#e74c3c'}">
                ${displayValues.humidity} ${compareHumidity ? '✓' : '✗'}
            </span>
        </div>
    `;
    
    pageDisplay.appendChild(displayTitle);
    pageDisplay.appendChild(displayContent);
    flowContainer.appendChild(pageDisplay);
    
    // 4. 问题诊断
    const diagnosis = document.createElement('div');
    diagnosis.style.padding = '10px';
    diagnosis.style.backgroundColor = '#2c3e50';
    diagnosis.style.borderRadius = '5px';
    
    const diagnosisTitle = document.createElement('div');
    diagnosisTitle.textContent = '4. 问题诊断';
    diagnosisTitle.style.fontWeight = 'bold';
    diagnosisTitle.style.marginBottom = '5px';
    diagnosisTitle.style.color = '#3498db';
    
    const diagnosisContent = document.createElement('div');
    
    // 全部是占位符?
    const allPlaceholders = Object.values(displayValues).every(val => val === '--');
    
    // 有有效数据?
    const hasValidData = data && (
        (data.radar_heartrate !== undefined) || 
        (data.radar_breath !== undefined) ||
        (data.temp !== undefined) || 
        (data.humidity !== undefined)
    );
    
    // 数据匹配率
    const matchCount = [compareHeartRate, compareBreathRate, compareTemp, compareHumidity].filter(Boolean).length;
    const matchRate = Math.round((matchCount / 4) * 100);
    
    if (allPlaceholders && hasValidData) {
        diagnosisContent.innerHTML = `
            <div style="color:#e74c3c; font-weight:bold; margin-bottom:5px;">❌ 严重问题: API有数据但页面全是占位符</div>
            <div style="margin-bottom:5px;">可能原因:</div>
            <ol style="margin-top:5px; padding-left:20px;">
                <li>数据访问路径错误</li>
                <li>数据类型转换失败</li>
                <li>DOM更新函数异常</li>
            </ol>
            <div>建议修复: 检查updateDisplayData和updateElementText函数</div>
        `;
    } else if (!hasValidData) {
        diagnosisContent.innerHTML = `
            <div style="color:#f39c12; font-weight:bold; margin-bottom:5px;">⚠️ API数据缺失</div>
            <div>API返回的数据中没有找到需要的字段</div>
            <div style="margin-top:5px;">建议: 检查后端API响应格式</div>
        `;
    } else if (matchRate < 100) {
        diagnosisContent.innerHTML = `
            <div style="color:#f39c12; font-weight:bold; margin-bottom:5px;">⚠️ 数据匹配率: ${matchRate}%</div>
            <div>有些字段未正确显示在页面上</div>
            <div style="margin-top:5px;">建议: 检查不匹配字段的处理逻辑</div>
        `;
    } else {
        diagnosisContent.innerHTML = `
            <div style="color:#2ecc71; font-weight:bold;">✅ 数据显示正常 (匹配率: ${matchRate}%)</div>
        `;
    }
    
    diagnosis.appendChild(diagnosisTitle);
    diagnosis.appendChild(diagnosisContent);
    flowContainer.appendChild(diagnosis);
    
    // 添加更新按钮
    const updateSection = document.createElement('div');
    updateSection.style.marginTop = '15px';
    updateSection.style.textAlign = 'center';
    
    const updateButton = document.createElement('button');
    updateButton.textContent = '🔄 更新测试数据';
    updateButton.style.backgroundColor = '#3498db';
    updateButton.style.color = 'white';
    updateButton.style.border = 'none';
    updateButton.style.padding = '8px 15px';
    updateButton.style.borderRadius = '5px';
    updateButton.style.cursor = 'pointer';
    updateButton.onclick = function() {
        // 触发测试数据显示
        if (typeof testDataDisplay === 'function') {
            testDataDisplay();
            setTimeout(() => {
                // 刷新可视化调试器
                dataDebugger();
            }, 500);
        } else {
            alert('测试数据函数未找到');
        }
    };
    
    updateSection.appendChild(updateButton);
    flowContainer.appendChild(updateSection);
    
    debuggerContainer.appendChild(flowContainer);
    document.body.appendChild(debuggerContainer);
}

// 强制测试按钮
function addDataDebuggerButton() {
    const btn = document.createElement('button');
    btn.textContent = '🔍 数据诊断';
    btn.style.position = 'fixed';
    btn.style.bottom = '20px';
    btn.style.right = '20px';
    btn.style.zIndex = '9999';
    btn.style.padding = '10px 15px';
    btn.style.backgroundColor = '#e74c3c';
    btn.style.color = 'white';
    btn.style.border = 'none';
    btn.style.borderRadius = '5px';
    btn.style.cursor = 'pointer';
    btn.style.fontWeight = 'bold';
    btn.style.boxShadow = '0 2px 5px rgba(0,0,0,0.2)';
    
    btn.onclick = function() {
        dataDebugger();
        // 同时显示调试面板
        const debugPanel = document.getElementById('debugPanel');
        if (debugPanel) {
            debugPanel.style.display = 'block';
        }
    };
    
    document.body.appendChild(btn);
    console.log('✅ 诊断工具已添加到页面');
}

// 页面加载完成后添加按钮
if (document.readyState === 'complete') {
    addDataDebuggerButton();
} else {
    window.addEventListener('load', addDataDebuggerButton);
}
